package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/26 17:24
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private WeChatProperties weChatProperties;
    private static final String url = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 向微信小程序服务器发送请求得到openid
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        // 通过HttpClient向微信小程序服务端发送请求，得到json字符串类型的数据
        String json = HttpClientUtil.doGet(url, paramMap);
        // 将json字符串转换为json对象，比较容易获取其中的openid
        JSONObject jsonObject = JSON.parseObject(json);
        // 拿到openid
        String openId = jsonObject.getString("openid");
        log.info("openId = {}", openId);
        // 通过openid查找user表，如果存在用户，则直接返回，如果不存在，则注册后再返回
        User user = userMapper.getByOpenId(openId);
        if (user == null) {
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            // 保存到数据库后需要将自增主键id返回给user对象
            userMapper.save(user);
        }
        return user;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 存放日期序列
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放截止到每天的总用户数量
        List<Integer> totalUserList = new ArrayList<>();
        // 存放截止到每天的新用户数量
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 该天的开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 该天的结束时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            Integer totalUserNumber = userMapper.getUserNumber(map);
            if (totalUserNumber == null) {
                totalUserNumber = 0;
            }
            totalUserList.add(totalUserNumber);
            map.put("begin", beginTime);
            Integer newUserNumber = userMapper.getUserNumber(map);
            if (newUserNumber == null) {
                newUserNumber = 0;
            }
            newUserList.add(newUserNumber);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }
}
